package com.duofan.gmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.product.service.CategoryBrandRelationService;
import com.duofan.gmall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.product.dao.CategoryDao;
import com.duofan.gmall.product.entity.CategoryEntity;
import com.duofan.gmall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 1.查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 2.组成父子结构
        // 查询一级分类
        List<CategoryEntity> level1Menus = categoryEntities.stream()
                .filter((categoryEntity) ->
                    categoryEntity.getParentCid() == 0
                ).map((menu) -> {
                    menu.setChildren(getChildrens(menu, categoryEntities));
                    return menu;
                }).sorted((m1, m2) ->
                        (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort())
                ).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> catIds) {
        // TODO 检查菜单是否被别的地方引用
        // 开发中常使用逻辑删除
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = findParentPath(catelogId, paths);
        Collections.reverse(parentPaths);
        return paths.toArray(new Long[parentPaths.size()]);
    }

    @Override
    @Transactional
//    @CacheEvict(value = "category", key = "'getLevel1Categorys'")
//    @Caching(evict = { // 同时进行多个缓存操作(这里清空多个缓存)
//            @CacheEvict(value="category", key = "'getLevel1Categorys'"),
//            @CacheEvict(value="category", key = "'getCatalogJson'"),
//    })
    @CacheEvict(value = "category", allEntries = true) // 删除分区下所有数据
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        if(!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
//    @Cacheable({"category"}) // 每个缓存的数据都指定名称,按业务类型分
//    @Cacheable(value = {"category"}, key = "'getLevel1Categorys'")
    @Cacheable(value = "category", key = "#root.method.name", sync = true) // key使用方法名
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
//        return null;
    }

    @Override
    @Cacheable(value = "category", key = "#root.methodName")
    public Map<String,List<Catalog2Vo>> getCatalogJson() {
        List<CategoryEntity> categoriesAll = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParentCid(categoriesAll, 0L);
        Map<String,List<Catalog2Vo>> catalog2VosMap = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParentCid(categoriesAll, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if(categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类
                    List<CategoryEntity> categoryLevel3Entities = getParentCid(categoriesAll, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if(categoryLevel3Entities != null) {
                        catalog3Vos = categoryLevel3Entities.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        return catalog2VosMap;
    }

/*    @Override
    public Map<String,List<Catalog2Vo>> getCatalogJson() {
        // 空结果缓存,解决缓存穿透
        // 加锁,解决缓存击穿
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        // 如果缓存中没有数据
        if(StringUtils.isEmpty(catalogJSON)) {
            System.out.println("缓存不命中,查数据库...");
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedissonLock();
//            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
//            redisTemplate.opsForValue().set("catalogJSON", catalogJSON);
        }
        System.out.println("缓存命中,直接返回");
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
        return result;
    }*/

    public Map<String,List<Catalog2Vo>> getCatalogJsonFromDbWithRedissonLock() {
        // 锁的名字: 锁粒度,越细越快
        // 锁粒度: 11号商品,product-11-lock,应对高并发情况
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;
    }

    public Map<String,List<Catalog2Vo>> getCatalogJsonFromDbWithRedisLock() {
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111");
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", "111", 30, TimeUnit.SECONDS);
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 30, TimeUnit.SECONDS);
        if(lock) {
            System.out.println("获取分布式锁成功...");
            // 设置过期时间
//            redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                // 使用lua脚本保证删锁的原子性
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }

            // 释放锁
//            redisTemplate.delete("lock");

//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)) {
//                redisTemplate.delete("lock");
//            }
            return dataFromDb;
        } else {
            System.out.println("未获取到锁,重试...");
            // 加锁失败,重试
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }
    }


    /**
     * 从数据库查询并封装分类数据,本地锁
     * @return
     */
    public Map<String,List<Catalog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        // 1.锁当前对象this
        // Spring Boot所有对象在容器中都是单例的
        // 2.方法加锁
        synchronized (this) {
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            if(!StringUtils.isEmpty(catalogJSON)) {
                Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>(){});
                return result;
            }

            Map<String, List<Catalog2Vo>> catalog2VosMap = getDataFromDb();
            // 数据转JSON,JSON全语言全平台兼容
            catalogJSON = JSON.toJSONString(catalog2VosMap);
            // 设置过期时间,解决雪崩问题
            redisTemplate.opsForValue().set("catalogJSON", catalogJSON, 1, TimeUnit.DAYS);
            return catalog2VosMap;
        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        // 优化: 将数据库多次查询变为一次
        List<CategoryEntity> categoriesAll = baseMapper.selectList(null);

        List<CategoryEntity> level1Categorys = getParentCid(categoriesAll, 0L);

        Map<String,List<Catalog2Vo>> catalog2VosMap = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 查一级分类的所有二级分类
            List<CategoryEntity> categoryEntities = getParentCid(categoriesAll, v.getCatId());
            List<Catalog2Vo> catalog2Vos = null;
            if(categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    // 找当前二级分类的三级分类
                    List<CategoryEntity> categoryLevel3Entities = getParentCid(categoriesAll, l2.getCatId());
                    List<Catalog2Vo.Catalog3Vo> catalog3Vos = null;
                    if(categoryLevel3Entities != null) {
                        catalog3Vos = categoryLevel3Entities.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return catalog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catalog2Vo.setCatalog3List(catalog3Vos);
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));
        // 数据转JSON,JSON全语言全平台兼容
        String catalogJSON = JSON.toJSONString(catalog2VosMap);
        // 设置过期时间,解决雪崩问题
        redisTemplate.opsForValue().set("catalogJSON", catalogJSON, 1, TimeUnit.DAYS);
        return catalog2VosMap;
    }


    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoriesAll, Long parentCid) {
        List<CategoryEntity> collect = categoriesAll.stream().filter(item -> item.getParentCid() == parentCid)
                .collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if(categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(e ->
                e.getParentCid() == root.getCatId()
        ).map(e -> {
            e.setChildren(getChildrens(e, all));
            return e;
        }).sorted((m1, m2) ->
                (m1.getSort() == null ? 0 : m1.getSort()) - (m2.getSort() == null ? 0 : m2.getSort())
        ).collect(Collectors.toList());
        return children;
    }
}